/**
 * 在这里定义与报名相关的路由处理函数，供/router/signUp.js模块使用
 */

// 导入db模块
const db = require('../db/index')

// 报名
exports.toSignUp = (req, res) => {
  const signUpInfo = req.body
  // 查询是否有学号重复的报名信息（判断是否重复报名）
  const sqlStr = 'select * from signup where studentId=?'
  db.query(sqlStr, [signUpInfo.studentId], (err, result) => {
    if (err) {
      return res.send({ status: 1, message: err.message })
    }
    // 未出错，判断是否重复报名
    if (result.length > 0) {
      // 重复报名，则更新报名信息
      const updateSqlStr = 'update signup set class=?, focus=?, time=?, qqNumber=?, userId=? where studentId=?'
      db.query(
        updateSqlStr,
        [signUpInfo.professionClass, signUpInfo.focus, signUpInfo.time, signUpInfo.qqNumber, signUpInfo.userId, signUpInfo.studentId],
        (err, result) => {
          if (err) {
            return res.send({ status: 1, message: err.message })
          }
          // 未出错，更新报名信息
          // 更新报名信息成功
          res.send({ status: 0, message: '更新报名信息成功' })
        }
      )
    } else {
      // 第一次报名，则直接插入报名信息
      const insertSqlStr =
        'insert into signup (name, class, focus, time, phoneNumber, qqNumber, studentId, userId) values (?, ?, ?, ?, ?, ?, ?, ?)'
      db.query(
        insertSqlStr,
        [signUpInfo.name, signUpInfo.professionClass, signUpInfo.focus, signUpInfo.time, signUpInfo.phoneNumber, signUpInfo.qqNumber, signUpInfo.studentId, signUpInfo.userId],
        (err, result) => {
          if (err) {
            return res.send({ status: 1, message: err.message })
          }
          // 未出错，插入报名信息
          // 报名成功
          res.send({ status: 0, message: '报名成功' })
        }
      )
    }
  })
}

// 查看报名信息
exports.checkMyProfile = (req, res) => {
  const userInfo = req.body
  const sqlStr = 'select name, class, focus, time, phoneNumber, qqNumber from signup where studentId=?'
  db.query(sqlStr, [userInfo.studentId], (err, result) => {
    // 查询出错
    if (err) {
      return res.send({ status: 1, message: err.message })
    }
    // 未出错，判断是否查询到数据
    if (result.length === 0) {
      return res.send({ status: 1, message: '没有该用户的报名信息' })
    } else {
      return res.send({
        status: 0,
        message: '查询报名信息成功',
        name: result[0].name,
        class: result[0].class,
        focus: result[0].focus,
        time: result[0].time,
        phoneNumber: result[0].phoneNumber,
        qqNumber: result[0].qqNumber
      })
    }
  })
}